package com.music.service.twitter.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.music.service.jdosupport.PMF;
import com.music.service.twitter.beans.TwitterServiceBean;
import com.music.service.twitter.constants.TwitterState;

public class TwitterDAOImpl implements TwitterDAO {

	public void deleteTwitter(Long pMemberId) {
		
		if(pMemberId == null){
			throw new IllegalArgumentException("pMemberId is null");
		}
		TwitterServiceBean twitter = getTwitter(pMemberId);

		if (twitter != null) {

			twitter.setState(TwitterState.DELETED);
			PersistenceManager persistenceManager = PMF.get()
					.getPersistenceManager();
			try {
				persistenceManager.makePersistent(twitter);
			} finally {
				persistenceManager.close();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public TwitterServiceBean getTwitter(Long pMemberId) {
		if(pMemberId == null){
			throw new IllegalArgumentException("pMemberId is null");
		}
		
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();

		Query query = persistenceManager.newQuery(TwitterServiceBean.class,
				"memberId == " + pMemberId + " && state == twitterStateParam");

		query.declareParameters("int twitterStateParam");
		List<TwitterServiceBean> results;
		results = (List<TwitterServiceBean>) query.execute(TwitterState.ACTIVE.getState());

		if (results != null && !results.isEmpty()) {
			return results.get(0);
		}
		return null;
	}

	public TwitterServiceBean insertTwitter(TwitterServiceBean pTwitter) {
		
		if(pTwitter == null){
			throw new IllegalArgumentException("pTwitter is null");
		}
		
		// default set to active.
		pTwitter.setState(TwitterState.ACTIVE);
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();
		try {
			pTwitter = persistenceManager.makePersistent(pTwitter);
		} finally {
			persistenceManager.close();
		}
		return pTwitter;
	}

}
